import json
import os
import subprocess
import re
import sublime
import sublime_plugin


class GolearnerRunCmdlineCommand(sublime_plugin.WindowCommand):
  def run(self):
    def on_done(iptStr):
      if iptStr != initStr:
        objJson["cmd_str"]=iptStr
        fJson=open(pathJson, mode='w')
        json.dump(objJson, fJson)
        fJson.close()


      cmdLine=sublime.expand_variables(iptStr, variables)
      win.run_command("show_panel", {"panel": "console"})
      print('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n----------------------------------------------------------------\n在目录'+variables["file_path"]+'下执行命令：\n'+cmdLine)
      p=subprocess.Popen(cmdLine, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=variables["file_path"])
      (out,err)=p.communicate()
      print("----------------------------------------------------------------\n标准输出：\n"+out.decode()+"\n----------------------------------------------------------------\n错误输出：\n"+err.decode()+"\n----------------------------------------------------------------\n\n\n\n\n\n\n\n\n")


    pkgDir=sublime.packages_path()
    pathJson=os.path.join(pkgDir, "GoLearner", "GoLearner.json")
    

    try:
      fJson=open(pathJson, mode='x')
    except FileExistsError:
      pass
    else:
      fJson.write('''{
  "cmd_str": "go run $file",
  "work_dir": "$file_path"
}''')
      fJson.close()

    fJson=open(pathJson)
    objJson=json.load(fJson)
    fJson.close()

    win=self.window
    variables=win.extract_variables()
    initStr=objJson["cmd_str"]

    win.show_input_panel("命令行:", initStr, on_done, None, None)


